package com.abel.classloader;

import com.alibaba.fastjson.JSON;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLClassLoader;

/**
 * @author xiachao
 * @date 2019/1/2
 */
public class MyClassLoader extends ClassLoader{

    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        MyClassLoader loader = new MyClassLoader();
        String classPath = "/Users/heaveneleven/IdeaProjects/headlineback-web/target/headlineback-web/WEB-INF/classes/com/dianping/headline/back/entity/keep/DailyCounter.class";
        Class clazz = loader.findClass(classPath);
        System.out.println(JSON.toJSONString(clazz));
        Object obj = clazz.newInstance();
        System.out.println(JSON.toJSONString(obj));
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = null;
        try {
            classData = this.findClassAsStream(name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (classData == null) {
            throw new ClassNotFoundException();
        } else {
            return defineClass("com.dianping.headline.back.entity.keep.DailyCounter", classData, 0, classData.length);
        }
    }

    public byte [] findClassAsStream(String name) throws IOException {
        InputStream inputStream = new FileInputStream(name);
        ByteArrayOutputStream byteStrem = new ByteArrayOutputStream();
        byte [] buff = new byte[1024];
        int len;
        while((len = inputStream.read(buff)) > 0){
            byteStrem.write(buff, 0, len);
        }
        inputStream.close();
        byteStrem.close();
        return byteStrem.toByteArray();
    }
}
